package servlet;

import dao.MovieMapper;
import org.apache.ibatis.session.SqlSession;
import utils.MyBatisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/ListServlet")
public class ListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        MovieMapper mapper = sqlSession.getMapper(MovieMapper.class);

        String pageNos = req.getParameter("pageNo");

        int pageSize = 2;
        int pageNo = 1;
        if(pageNos != null){
            pageNo = Integer.parseInt(pageNos);
        }

        int totalCount = mapper.count();

        req.getSession().setAttribute("totalCount",totalCount);

        int totalPages = totalCount / pageSize;
        if((totalCount % pageSize) != 0){
            totalPages++;
        }

        req.getSession().setAttribute("totalPages",totalPages);
        req.getSession().setAttribute("pageNo",pageNo);
        req.getSession().setAttribute("count",mapper.count());
        req.getSession().setAttribute("list",mapper.list((pageNo-1)*pageSize,pageSize));
        MyBatisUtil.closeSqlSession(sqlSession);
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
